package com.cxc.news.controller;

import com.cxc.news.pojo.News;
import com.cxc.news.pojo.User;
import com.cxc.news.service.NewsService;
import com.cxc.news.service.UserService;
import com.cxc.news.utils.Value;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;
import java.util.Map;

@Controller
public class AdminController {

    @Autowired
    private NewsService newsService;
    @Autowired
    private UserService userService;

    @GetMapping("/admin/{pageNum}")
    public String toAdmin(@PathVariable("pageNum") Integer pageNum,
                          Map map){
        if (pageNum == -1){
            pageNum = 1;
        }
        List<User> users = userService.getUserList();
        if (users != null){
            map.put("users",users);
        }

        PageInfo<News> pageInfo = newsService.listNews(pageNum,5,null);
        if (pageInfo != null){
            map.put("pages",pageInfo);
        }

        return Value.PATH_ADMIN_INDEX;
    }

    /**
     * 管理员删除新闻
     * @param newsId
     * @return
     */
    @GetMapping("/admin/delnews/{pageNum}/{newsId}")
    public String deleteNews(@PathVariable("newsId") Long newsId,
                             @PathVariable("pageNum") Long pageNum){
        if (newsService.getNews(newsId) != null){
            newsService.deleteNews(newsId);
        }
        return "redirect:/admin/"+ pageNum;
    }
}
